package org.csu.onlineedubackend.mapper;

import org.apache.ibatis.annotations.*;
import org.csu.onlineedubackend.entity.ConversationParticipant;
import org.csu.onlineedubackend.entity.User;

import java.util.List;

@Mapper
public interface ConversationParticipantMapper {
    
    @Insert("INSERT INTO conversation_participants (conversation_id, user_id, unread_count) VALUES (#{conversationId}, #{userId}, #{unreadCount})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(ConversationParticipant participant);
    
    @Select("SELECT * FROM conversation_participants WHERE conversation_id = #{conversationId} AND user_id = #{userId}")
    ConversationParticipant findByConversationAndUser(@Param("conversationId") Long conversationId, @Param("userId") Integer userId);
    
    @Select("SELECT * FROM conversation_participants WHERE conversation_id = #{conversationId}")
    List<ConversationParticipant> findByConversationId(Long conversationId);
    
    @Select("SELECT u.* FROM user u " +
            "JOIN conversation_participants cp ON u.id = cp.user_id " +
            "WHERE cp.conversation_id = #{conversationId}")
    List<User> findParticipantsByConversationId(Long conversationId);
    
    @Update("UPDATE conversation_participants SET unread_count = unread_count + 1 WHERE conversation_id = #{conversationId} AND user_id != #{excludeUserId}")
    int incrementUnreadCount(@Param("conversationId") Long conversationId, @Param("excludeUserId") Integer excludeUserId);
    
    @Update("UPDATE conversation_participants SET unread_count = 0 WHERE conversation_id = #{conversationId} AND user_id = #{userId}")
    int resetUnreadCount(@Param("conversationId") Long conversationId, @Param("userId") Integer userId);
    
    @Delete("DELETE FROM conversation_participants WHERE conversation_id = #{conversationId} AND user_id = #{userId}")
    int deleteByConversationAndUser(@Param("conversationId") Long conversationId, @Param("userId") Integer userId);

    @Delete("DELETE FROM conversation_participants WHERE conversation_id = #{conversationId}")
    int deleteByConversationId(Long conversationId);
} 